﻿
var useremail = '';


//Gmail:

function deleteAllCookies() {
    var cookies = document.cookie.split(";");

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var eqPos = cookie.indexOf("=");
        var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}

function Open(userid) {
    //alert(document.cookie);
    deleteAllCookies();
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var j = JSON.parse(xmlhttp.responseText);
            //alert(j.url);
            var cookies = j.url.split(";");
            //alert(cookies[2]);
            for (var i = 0; i < cookies.length; i++) {
                document.cookie = cookies[i];
            }
            //alert(document.cookie);

            //now reload the page:
            location.reload(true);
        }
    }
    xmlhttp.open("GET", "/User/Open/?user=" + userid, true);
    xmlhttp.send();
}


(function () {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/client:plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();

function signinCallback(authResult) {
    if (authResult['status']['signed_in']) {
        // the user signed in successfuly
        // Update the app to reflect a signed in user
        // Hide the sign-in button now that the user is authorized, for example:
        gapi.client.load('oauth2', 'v2', function () {
            gapi.client.oauth2.userinfo.get().execute(function (resp) {
                    // Shows user email
                    if (authResult['status']['method'] == 'PROMPT')
                    {
                        Open(resp.email);
                    }
                    useremail = resp.email;
                })
            });
        
        document.getElementById('signinButton').setAttribute('style', 'display: none');
        document.getElementById('signoutLink').setAttribute('style', 'visibility: visible');
        getAvailableCalendars();
    } else {
        // user access denied
        // Update the app to reflect a signed out user
        // Possible error values:
        //   "user_signed_out" - User is signed-out
        //   "access_denied" - User denied access to your app
        //   "immediate_failed" - Could not automatically log in the user
        calendarIdToSummaryMap = undefined;
        document.getElementById('signoutLink').setAttribute('style', 'visibility: hidden');
        console.log('Sign-in state: ' + authResult['error']);
    }
}

function disconnectUser(access_token) {
    var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' +
        access_token;

    // Perform an asynchronous GET request.
    $.ajax({
        type: 'GET',
        url: revokeUrl,
        async: false,
        contentType: "application/json",
        dataType: 'jsonp',
        success: function (nullResponse) {
            // Do something now that user is disconnected
            // The response is always undefined.
        },
        error: function (e) {
            // Handle the error
            // console.log(e);
            // You could point users to manually disconnect if unsuccessful
            // https://plus.google.com/apps
        }
    });
    gapi.auth.signOut();

    document.getElementById('signinButton').setAttribute('style', 'display: block');
    
    //now clear all cookies:
    deleteAllCookies();
    useremail = '';
}

//Facebook:

window.fbAsyncInit = function () {
    FB.init({
        appId: '557311297717518',
        status: true, // check login status
        cookie: true, // enable cookies to allow the server to access the session
        xfbml: true  // parse XFBML
    });

    // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
    // for any authentication related change, such as login, logout or session refresh. This means that
    // whenever someone who was previously logged out tries to log in again, the correct case below 
    // will be handled. 
    FB.Event.subscribe('auth.authResponseChange', function (response) {
        // Here we specify what we do with the response anytime this event occurs. 
        if (response.status === 'connected') {
            // The response object is returned with a status field that lets the app know the current
            // login status of the person. In this case, we're handling the situation where they 
            // have logged in to the app.
            testAPI();
        } else if (response.status === 'not_authorized') {
            // In this case, the person is logged into Facebook, but not into the app, so we call
            // FB.login() to prompt them to do so. 
            // In real-life usage, you wouldn't want to immediately prompt someone to login 
            // like this, for two reasons:
            // (1) JavaScript created popup windows are blocked by most browsers unless they 
            // result from direct interaction from people using the app (such as a mouse click)
            // (2) it is a bad experience to be continually prompted to login upon page load.
            FB.login();
        } else {
            // In this case, the person is not logged into Facebook, so we call the login() 
            // function to prompt them to do so. Note that at this stage there is no indication
            // of whether they are logged into the app. If they aren't then they'll see the Login
            // dialog right after they log in to Facebook. 
            // The same caveats as above apply to the FB.login() call here.
            FB.login();
        }
    });
};

// Load the SDK asynchronously
(function (d) {
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) { return; }
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
}(document));

// Here we run a very simple test of the Graph API after login is successful. 
// This testAPI() function is only called in those cases. 
function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function (response) {
        console.log('Good to see you, ' + response.name + '.');
    });
}

function logout() {
    FB.logout(function (response) {
        // user is now logged out
    });
}

function collectFacebookGroups(coursesList, devId) {
    document.getElementById(devId).innerHTML = '';
    for (var c in coursesList) {
        var urlCall = "/search?q=" + coursesList[c].courseNumber + "&type=group&access_token=";
        FB.api(urlCall, function (response) {
            searchResult = '';
            searchResult += 'Suggested groups for ' + coursesList[c].courseNumber + ':<br>';
            for (var g in response.data) {
                searchResult += "<a target='_blank' href='http://www.facebook.com/" + response.data[g].id + "'>"
                                + response.data[g].name + "</a>" + "<br>";
            }
            document.getElementById(devId).innerHTML += searchResult;
        });
    }
}

